//
//  LTTestwebViewController.swift
//  LittleThink
//
//  Created by wei.feng on 2024/11/4.
//

import UIKit
import WebKit
import Foundation
import Toast_Swift
import IQKeyboardManagerSwift
import TZImagePickerController
import SnapKit

class LTTestwebViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        view.addSubview(textView)
        view.addSubview(stackView)
        
        stackView.addArrangedSubview(clearBtn)
        stackView.addArrangedSubview(pasteBtn)
        stackView.addArrangedSubview(downloadBtn)
        
        textView.snp.makeConstraints { make in
            make.top.equalTo(100)
            make.centerX.equalToSuperview()
            make.width.equalTo(pixw(p: 300))
            make.height.equalTo(pixw(p: 160))
        }
        
        stackView.snp.makeConstraints { make in
            make.top.equalTo(textView.snp.bottom).offset(pixw(p: 10))
            make.left.right.equalTo(textView)
            make.height.equalTo(pixw(p: 40))
        }
                
        view.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(SCREEN_HEIGHT * 2)
            make.height.equalTo(SCREEN_HEIGHT)
        }
        
#if DEBUG
        webView.snp.remakeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(stackView.snp.bottom)
            make.bottom.equalTo(0)
        }
        #endif
        
    }
    
    func matchUrlFromShareText(_ txt: String) -> String {
        var text = txt as NSString
        let range = text.range(of: "https")
        if range.location != NSNotFound {
            text = text.substring(from: range.location) as NSString
            let array = text.components(separatedBy: " ")
            if array.count > 0 {
                return array[0]
            }
        }
        
        return txt
    }
    
    lazy var textView: IQTextView = {
        let view = IQTextView()
        view.layer.borderColor = UIColor.black.cgColor
        view.layer.borderWidth = 1
        view.layer.cornerRadius = 8
        view.backgroundColor = UIColor(white: 240.0/255.0, alpha: 1)
        view.placeholder = "请将抖音分享链接粘贴到输入框"
        return view
    }()
    
    lazy var stackView: UIStackView = {
        let view = UIStackView()
        view.axis = .horizontal
        view.distribution = .fillEqually
        view.alignment = .fill
        view.spacing = 10
        return view
    }()

    lazy var clearBtn: UIButton = {
        let view = UIButton.create(title: "Clear", titleColor: .black)
        view.addTarget(self, action: #selector(onClickClearBtn), for: .touchUpInside)
        view.layer.borderColor = UIColor.black.cgColor
        view.layer.borderWidth = 1
        view.layer.cornerRadius = 8
        view.delayTime = 1.0
        return view
    }()
    
    @objc func onClickClearBtn() {
        textView.text = nil
    }

    lazy var pasteBtn: UIButton = {
        let view = UIButton.create(title: "粘贴", titleColor: .black)
        view.addTarget(self, action: #selector(onClickPasteBtn), for: .touchUpInside)
        view.layer.borderColor = UIColor.black.cgColor
        view.layer.borderWidth = 1
        view.layer.cornerRadius = 8
        view.delayTime = 1.0
        return view
    }()
    
    @objc func onClickPasteBtn() {
        textView.text = UIPasteboard.general.string
    }

    lazy var downloadBtn: UIButton = {
        let view = UIButton.create(title: "下载", titleColor: .black)
        view.addTarget(self, action: #selector(onClickDownloadBtn), for: .touchUpInside)
        view.layer.borderColor = UIColor.black.cgColor
        view.layer.borderWidth = 1
        view.layer.cornerRadius = 8
        view.delayTime = 1.0
        return view
    }()
    
    @objc func onClickDownloadBtn() {
        guard let urlString = textView.text else {
            let alert = UIAlertController(title: "error", message: "请将抖音分享链接粘贴到输入框", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel))
            self.present(alert, animated: true)
            return
        }
        if let url = URL(string: matchUrlFromShareText(urlString)) {
            view.makeToastActivity(.center)
            webView.load(URLRequest(url: url))
        } else {
            let alert = UIAlertController(title: "error", message: "链接有误", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .cancel))
            self.present(alert, animated: true)
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    lazy var webView: WKWebView = {
        let view = WKWebView(frame: .zero, configuration: WKWebViewConfiguration())
        view.navigationDelegate = self
        return view
    }()

    private func downloadVideo(_ url: URL, _ callback:((Bool, Error?) -> Void)? = nil) {
        
        let task = URLSession.shared.downloadTask(with: URLRequest(url: url)) { (cacheURL, response, error) in
            if let videoPath = cacheURL, FileManager.default.fileExists(atPath: videoPath.path) {
                let tempPath = FileManager.TmpDirectory().appending("/\(Date().timeIntervalSince1970).mp4")
                let result = FileManager.copyFile(type: .file, fromeFilePath: videoPath.path, toFilePath: tempPath)
                if result.isSuccess {
                    TZImageManager().saveVideo(with: NSURL(fileURLWithPath: tempPath) as URL) { asset, err in
                        if let err = err {
                            callback?(false, err)

                        } else {
                            callback?(true, nil)
                        }
                    }
                } else {
#if DEBUG
                    print("====\(result.error)")
#endif
                    callback?(false, NSError(domain: result.error, code: -1))
                }
                
            } else {
                callback?(false, error)
            }
        }
        task.resume()
    }

    //document.getElementById("video-player").src

    private var trying = 0
    func getVideoUrl(_ callback: ((URL?, Error?) -> Void)? = nil) {
        trying += 1
        let js = """
document.getElementsByTagName('video')[0].currentSrc
"""
        webView.evaluateJavaScript(js) { (response, error) in
#if DEBUG
            print("==== get url finish, \nurl: \(response) \n error: \(error?.localizedDescription)")
#endif
            if let videoUrl = response as? String, let url = URL(string: videoUrl) {
                self.trying = 0
                callback?(url, error)
            } else {
                if self.trying > 3 {
                    self.trying = 0
                    callback?(nil, error)
                } else {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        self.getVideoUrl(callback)
                    }
                }
            }
        }
    }
    
    func downloadAndSaveVideoToPhoto() {
        getVideoUrl { url, error in
            if let url = url {
                self.downloadVideo(url) { success, err in
                    self.view.hideToastActivity()
                    if success {
                        let alert = UIAlertController(title: "Success", message: "视频已保存到相册", preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
                        self.present(alert, animated: true)
                    } else {
                        let alert = UIAlertController(title: "error", message: err?.localizedDescription, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel))
                        self.present(alert, animated: true)
                    }
                }
            } else {
                self.view.hideToastActivity()
                let alert = UIAlertController(title: "error", message: error?.localizedDescription, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel))
                self.present(alert, animated: true)
            }
        }
    }
}

extension LTTestwebViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url
#if DEBUG
        print("===== webView start \(url)")
#endif
        decisionHandler(.allow)
    }
        
//    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
//        dbLog("===== webView response === \(navigationResponse.response)")
//        decisionHandler(.allow)
//    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        downloadAndSaveVideoToPhoto()
    }
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        //
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        downloadAndSaveVideoToPhoto()
    }
}
